<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>橡皮筋式选取框</title>
    <style>
        body {}

        #canvas {
            margin-left: 20px;
            margin-right: 0;
            margin-bottom: 20px;
            border: thin solid #aaaaaa;
            cursor: crosshair;
            padding: 0;
        }

        #controls {
            margin: 20px 0px 20px 20px;
        }

        #rubberbandDiv {
            position: absolute;
            border: thin inset blue;
            cursor: crosshair;
            display: none;
        }
    </style>
</head>

<body>
    <div id='controls'>
        <input type='button' id='resetButton' value='Reset' />
    </div>

    <div id='rubberbandDiv'></div>

    <canvas id='canvas' width='800' height='520'>
        Canvas not supported
    </canvas>
    <!-- <script src="example.js"></script> -->
    <script>
        const canvas = document.getElementById('canvas')
        const div = document.getElementById('rubberbandDiv')
        const resetBtn = document.getElementById('resetButton')
        const ctx = canvas.getContext('2d');
        const image = new Image();
        let draw = false;

        image.src = 'img.jpg';
        image.onload = function () {
            ctx.drawImage(image, 0, 0, canvas.width, canvas.height)
        }

        canvas.addEventListener('mousedown', function (e) {
            div.oX = e.clientX
            div.oY = e.clientY
            draw = true

        })
        window.addEventListener('mousemove', function (e) {
            e.preventDefault();
            div.width = Math.abs(e.clientX - div.oX)
            div.height = Math.abs(e.clientY - div.oY)

            div.left = e.clientX < div.oX ? e.clientX : div.oX
            div.top = e.clientY < div.oY ? e.clientY : div.oY
            if (draw) {
                div.style.cssText = `top:${div.top}px;left:${div.left}px;width:${div.width}px;height:${div.height}px;display:inline`
            }
        })
        div.addEventListener('mouseup', function (e) {
            draw = false
            const canvasBox = canvas.getBoundingClientRect();
            ctx.drawImage(canvas, div.left - canvasBox.left, div.top - canvasBox.top, div.width, div.height, 0, 0, canvas.width, canvas.height)
            div.style.display = 'none'
        })
        resetBtn.addEventListener('click', function () {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.drawImage(image, 0, 0, canvas.width, canvas.height)
        })
    </script>
</body>

</html>